{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e8062c41",
   "metadata": {},
   "source": [
    "# Calculating Gradient Using Quantum Circuit\n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8947f99",
   "metadata": {},
   "source": [
    "## Overview\n",
    "\n",
    "When using variational quantum algorithms like [Variational Quantum Eigensolver (VQE)](../quantum_simulation/VQE_EN.ipynb) and [Quantum Approximate Optimization Algorithm (QAOA)](../combinatorial_optimization/QAOA_EN.ipynb), which involves varying parameters of quantum circuit to minimize an objective function of interest, it brings out an important question - what are the ways to calculate the gradient of a parameterized quantum circuit? Since the objective function is being evaluated using a quantum circuit, it's necessary to evaluate its gradient using quantum algorithms as well. Compared with computing gradient classically, this is more challenging for sure. Below we provide three different methods to accomplish this task on a quantum computer. And here we demonstrate the code and simulate their effect of running on a quantum computer using Paddle Quantum."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61395a57",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "Suppose the objective function is the typical parameterized cost function used in VQA: $O(\\theta) = \\left\\langle00\\right| U^{\\dagger}(\\theta)HU(\\theta) \\left|00\\right\\rangle$ where H is a Hamiltonian, $U(\\theta)$ represents the parameterized quantum circuit and $\\theta = [\\theta_1, \\theta_2, \\dots, \\theta_n]$ is a list of trainable parameters in the circuit, then our goal is to find\n",
    "\n",
    "$$\n",
    "\\nabla O(\\theta) = \\begin{bmatrix} \\frac{\\partial O}{\\partial \\theta_1} \\\\ \\frac{\\partial O}{\\partial \\theta_2}\\\\ \\vdots\\\\ \\frac{\\partial O}{\\partial \\theta_n} \\end{bmatrix}.\n",
    "\\tag{1}\n",
    "$$\n",
    "\n",
    "First, let's import all the required packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5e438617",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import paddle\n",
    "from paddle_quantum.circuit import UAnsatz\n",
    "from paddle_quantum.utils import pauli_str_to_matrix, Hamiltonian\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec29c111",
   "metadata": {},
   "source": [
    "Then, let's construct our $U(\\theta)$ and Hamiltonian $H$ of the objective function $O(\\theta) = \\left\\langle00\\right| U^{\\dagger}(\\theta)HU(\\theta) \\left|00\\right\\rangle$.\n",
    "\n",
    "We will demonstrate our example on a 2-qubit quantum circuit, constructing $U(\\theta)$ with randomly generated theta of size four. We choose our Hamiltonian H to be $H = Z \\otimes Z$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "00c29cb2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hamiltonian H: \n",
      " [[ 1.+0.j  0.+0.j  0.+0.j  0.+0.j]\n",
      " [ 0.+0.j -1.+0.j  0.+0.j  0.+0.j]\n",
      " [ 0.+0.j  0.+0.j -1.+0.j  0.+0.j]\n",
      " [ 0.+0.j  0.+0.j  0.+0.j  1.+0.j]]\n",
      "\n",
      "U(theta):\n",
      "--Ry(5.690)----*----x----Ry(3.107)--\n",
      "               |    |               \n",
      "--Ry(2.521)----x----*----Ry(0.437)--\n",
      "                                    \n"
     ]
    }
   ],
   "source": [
    "# Define Hamiltonian H\n",
    "pauli_str = [[1.0, 'Z0,Z1']]\n",
    "H = Hamiltonian(pauli_str)\n",
    "\n",
    "# Randomly generate parameters in range from 0 to 2*PI\n",
    "theta_np = np.random.uniform(0, 2 * np.pi, 4)\n",
    "# Warning: Note that when defining theta, if we mark stop_gradient=False, then this parameter is trainable; \n",
    "# otherwise, the parameter will be treated as constant, its gradient will not be calculated and it will not be updated in training process.\n",
    "theta_tensor = paddle.to_tensor(theta_np, 'float64', stop_gradient=False)\n",
    "\n",
    "def U_theta(theta):\n",
    "    cir = UAnsatz(2)\n",
    "    cir.ry(theta[0], 0)\n",
    "    cir.ry(theta[1], 1)\n",
    "    cir.cnot([0, 1])\n",
    "    cir.cnot([1, 0])\n",
    "    cir.ry(theta[2], 0)\n",
    "    cir.ry(theta[3], 1)\n",
    "    cir.run_state_vector()\n",
    "    return cir\n",
    "\n",
    "print('Hamiltonian H: \\n', H.construct_h_matrix())\n",
    "print('\\nU(theta):')\n",
    "print(U_theta(theta_tensor))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc5028f6",
   "metadata": {},
   "source": [
    "## Finite Difference Method\n",
    "\n",
    "The Finite difference method is one of the most traditional and common numerical methods to estimate the gradient of a function. The main idea is that the error of the derivative of a function $f(x)$ tends to zero as $h$ tends to zero: \n",
    "\n",
    "$$\n",
    "f'(x)= \\lim_{h \\to 0}\\frac{f(x+h) - f(x)}{h}.\n",
    "\\tag{2}\n",
    "$$\n",
    "\n",
    "By choosing a sufficiently small $h$, we can get a good approximation of the derivative.\n",
    "\n",
    "For example, by using one type of finite difference, the central finite difference method, the objective function's gradient will be\n",
    "\n",
    "$$\n",
    "\\nabla O(\\theta) \\approx \\frac{O(\\theta+\\delta) - O(\\theta-\\delta)}{2\\delta} = \\frac{\\left\\langle00\\right| U^{\\dagger}(\\theta + \\delta)HU(\\theta + \\delta) \\left|00\\right\\rangle - \\left\\langle00\\right| U^{\\dagger}(\\theta - \\delta)HU(\\theta-\\delta) \\left|00\\right\\rangle)}{2\\delta}.\n",
    "\\tag{3}\n",
    "$$\n",
    "\n",
    "When implementing this, we can simply loop through the parameter list, shift the specific parameter in the original circuit and evaluate the objective function over and over again. There's no need to build extra circuits or using extra qubits.\n",
    "\n",
    "Using Paddle Quantum's built-in method, we can build the circuit of $U(\\theta)$, and compute the finite-difference gradient easily by passing in the corresponding Hamiltonian H and the delta. Note: The built-in method currently does not support assigning an input state or running on a noisy circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c836f71e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--Ry(5.690)----*----x----Ry(3.107)--\n",
      "               |    |               \n",
      "--Ry(2.521)----x----*----Ry(0.437)--\n",
      "                                    \n",
      "Gradient of this objective function is:  [-0.79156126  0.12584221 -0.26541629  0.78068313]\n"
     ]
    }
   ],
   "source": [
    "# We reuse the predefined Hamiltonian H and parameters of the circuit. \n",
    "# Again, be sure to mark stop_gradient=False when defining tensor for parameters of the circuit\n",
    "\n",
    "# Constructing circuit U(theta)\n",
    "cir = U_theta(theta_tensor)\n",
    "print(cir)\n",
    "\n",
    "# Calculating finite-difference gradient\n",
    "gradients = cir.finite_difference_gradient(H, delta=0.01)\n",
    "print(\"Gradient of this objective function is: \", gradients.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8055ed76",
   "metadata": {},
   "source": [
    "## Parameter-shift Method\n",
    "Again, we use this objective function $O(\\theta) = \\left\\langle0\\right| U^{\\dagger}(\\theta)HU(\\theta) \\left|0\\right\\rangle$ as our example. If $U(\\theta)$ can be written as $e^{-ia\\theta G}$ where $G$ has two unique eigenvalues $\\lambda_1$ and $\\lambda_2$, we can apply parameter-shift method to find its gradient [1]:\n",
    "\n",
    "$$\n",
    "\\nabla O(\\theta) = r \\left[O(\\theta+\\frac{\\pi}{4r}) - O(\\theta-\\frac{\\pi}{4r})\\right],\n",
    "\\tag{4}\n",
    "$$ \n",
    "\n",
    "where shift constant $r = \\frac{a}{2} (\\lambda_2 - \\lambda_1)$. Note that we're getting a theoretically exact gradient instead of an estimation like finite difference gradient. Moreover, this method doesn't require the construction of new circuits or adding ancilla qubits. Evaluations could be done just by changing the parameters inside the circuit.\n",
    "\n",
    "The fundamental rotation gates provided by Paddle Quantum are $R_x(\\theta), R_y(\\theta), R_z(\\theta)$ gates, which can be written as $e^{-i\\frac{1}{2}\\theta X}, e^{-i\\frac{1}{2}\\theta Y}, e^{-i\\frac{1}{2}\\theta Z}$ respectively. Since the eigenvalues of $X$, $Y$, and $Z$ gates are unique, which are -1 and 1, it's not hard to see that $r = \\frac{1}{2}$, and the gradient of those gates is just\n",
    "\n",
    "$$\n",
    "\\frac{1}{2}[ O(\\theta + \\frac{\\pi}{2}) - O(\\theta - \\frac{\\pi}{2})].\n",
    "\\tag{5}\n",
    "$$\n",
    "\n",
    "We will demonstrate this formula's derivation using a single rotation gate $R_x$."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81a1defe",
   "metadata": {},
   "source": [
    "### Derivation\n",
    "\n",
    "In this section, we will go through all the steps and arrive at the resulting formula for calculating $R_x$ gate's derivative. Using $R_x(\\theta)$ as $U(\\theta)$, we have\n",
    "\n",
    "$$\n",
    "O(\\theta) = \\left\\langle0\\right| R_x^{\\dagger}(\\theta)HR_x(\\theta) \\left|0\\right\\rangle.\n",
    "\\tag{6}\n",
    "$$\n",
    "\n",
    "Given that $R_x(\\theta) = e^{-i\\frac{1}{2}\\theta X}$, where $X$ is the Pauli-X matrix, we know $\\frac{\\partial}{\\partial \\theta}  R_x(\\theta) =-i\\frac{1}{2}Xe^{-i\\frac{\\theta}{2}X}=-i\\frac{1}{2}XR_x(\\theta)$.  Using the product rule, its derivative can be written as\n",
    "\n",
    "$$\n",
    "O'(\\theta) = \\left\\langle0\\right| [\\frac{i}{2}X] R_x^{\\dagger}(\\theta)HR_x(\\theta)\\left|0\\right\\rangle + \\left\\langle0\\right| R_x^{\\dagger}(\\theta)H [-\\frac{i}{2}X] R_x(\\theta)\\left|0\\right\\rangle.\n",
    "\\tag{7}\n",
    "$$\n",
    "\n",
    "We take out the shift constant $r$ in front for the purpose of later rearranging the equation using some trick, where $r$ for $R_x$ gate is $\\frac{1}{2}$. We have\n",
    "\n",
    "$$\n",
    "O'(\\theta) = r \\left\\langle0\\right| [\\frac{i}{2r}X] R_x^{\\dagger}(\\theta)HR_x(\\theta)\\left|0\\right\\rangle + \\left\\langle0\\right| R_x^{\\dagger}(\\theta)H [-\\frac{i}{2r}X] R_x(\\theta)\\left|0\\right\\rangle.\n",
    "\\tag{8}\n",
    "$$\n",
    "\n",
    "Since we recognize that for any operators $U$, $V$ and $Q$, and for an arbitrary state $|\\psi\\rangle$, \n",
    "\n",
    "$$\n",
    "\\langle\\psi|U^\\dagger QV|\\psi\\rangle + \\langle\\psi|V^\\dagger QU|\\psi\\rangle = \\frac{1}{2} \\big(\\langle\\psi|(U+V)^\\dagger Q(U+V)|\\psi\\rangle - \\langle\\psi|(U-V)^\\dagger Q(U-V)|\\psi\\rangle \\big),\n",
    "\\tag{9}\n",
    "$$\n",
    "\n",
    "we get \n",
    "\n",
    "$$\n",
    "O'(\\theta) = \\frac{r}{2} \\big( \\left\\langle0\\right|R_x^{\\dagger}(\\theta) [I + \\frac{i}{2r}X]H[I - \\frac{i}{2r}X]R_x(\\theta)\\left|0\\right\\rangle - \\left\\langle0\\right| R_x^{\\dagger}(\\theta) [I - \\frac{i}{2r}X] H [I+\\frac{i}{2r}X] R_x(\\theta)\\left|0\\right\\rangle \\big).\n",
    "\\tag{10}\n",
    "$$\n",
    "\n",
    "Using Euler's identity and knowing that $G$ has two unique eigenvalues, we can rewrite $U(\\theta)$ as $e^{-ia\\theta G} = I\\cos(r\\theta) - i\\frac{a}{r}G\\sin(r\\theta)$ [1]. Thus, we have $R_x(\\theta) = I\\cos(r\\theta) - i\\frac{1}{2r}X\\sin(r\\theta)$, we notice that \n",
    "\n",
    "$$\n",
    "R_x(\\frac{\\pi}{4r}) = I\\cos(\\frac{\\pi}{4}) - i\\frac{1}{2r}X\\sin(\\frac{\\pi}{4}) = \\frac{1}{\\sqrt2}(I-\\frac{i}{2r}X).\n",
    "\\tag{11}\n",
    "$$\n",
    "\n",
    "We can use the same method to get \n",
    "\n",
    "$$\n",
    "R_x(-\\frac{\\pi}{4r}) = \\frac{1}{\\sqrt2}(I+\\frac{i}{2r}X).\n",
    "\\tag{12}\n",
    "$$\n",
    "\n",
    "Thus, the equation can be simplified to\n",
    "\n",
    "$$\n",
    "O'(\\theta) = r\\big[ \\left\\langle0\\right|R_x^{\\dagger}(\\theta+\\frac{\\pi}{4r})HR_x(\\theta+\\frac{\\pi}{4r})\\left|0\\right\\rangle - \\left\\langle0\\right| R_x^{\\dagger}(\\theta-\\frac{\\pi}{4r}) H R_x(\\theta-\\frac{\\pi}{4r})\\left|0\\right\\rangle \\big],\n",
    "\\tag{13}\n",
    "$$\n",
    "\n",
    "and get the final formula,\n",
    "\n",
    "$$\n",
    "O'(\\theta) = r\\big[O(\\theta+\\frac{\\pi}{4r}) - O(\\theta-\\frac{\\pi}{4r}))\\big] = \\frac{1}{2}\\big[ O(\\theta + \\frac{\\pi}{2}) - O(\\theta - \\frac{\\pi}{2})\\big].\n",
    "\\tag{14}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c460666d",
   "metadata": {},
   "source": [
    "### Paddle Quantum implementation\n",
    "Here we demonstrate how to use Paddle Quantum's built-in parameter shift method to calculate the gradient. Note: The built-in method currently does not support assigning an input state or running on a noisy circuit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "18d78ca9",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--Ry(5.690)----*----x----Ry(3.107)--\n",
      "               |    |               \n",
      "--Ry(2.521)----x----*----Ry(0.437)--\n",
      "                                    \n",
      "Gradient of this objective function is:  [-0.79156457  0.12584274 -0.2654174   0.7806864 ]\n"
     ]
    }
   ],
   "source": [
    "# We reuse the predefined Hamiltonian H and parameters of the circuit. \n",
    "# Again, be sure to mark stop_gradient=False when defining tensor for parameters of the circuit.\n",
    "\n",
    "# Constructing circuit U(theta)\n",
    "cir = U_theta(theta_tensor)\n",
    "print(cir)\n",
    "\n",
    "gradients = cir.param_shift_gradient(H)\n",
    "print(\"Gradient of this objective function is: \", gradients.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2490a251",
   "metadata": {},
   "source": [
    "## Linear Combination of Unitary Gradients\n",
    "\n",
    "Building a parameterized circuit $U(\\theta)$ using Paddle Quantum requires many parameterized one-qubit and two-qubit gates like $R_x$ and $CR_x$. So we can rewrite $U(\\theta)$ as $U_{1}(\\theta_1)U_{2}(\\theta_2)\\cdots U_{m}(\\theta_m)$, where $U_i(\\theta_i)$ is one of the one-qubit and two-qubit gates and $m$ is the total number of parameterized gates in this circuit $U(\\theta)$. To get the gradient of an individual parameter, we consider this equation $\\frac{\\partial U(\\theta)}{\\partial \\theta_i}=U_{1}(\\theta_1)U_{2}(\\theta_2)\\cdots\\frac{\\partial U_i{(\\theta_i)}}{\\partial \\theta_i}\\cdots U_{m}(\\theta_m)$. We notice that as long as we know $\\frac{\\partial U_i{(\\theta_i)}}{\\partial \\theta_i}$ for all parameterized gates, we can get the gradients for all parameters easily [2]."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c98fb33",
   "metadata": {},
   "source": [
    "### Single qubit gate gradient\n",
    "\n",
    "Let's consider single qubit gates first. We also take $R_x(\\theta)$ as an example. In the previous sections, we've already shown that $\\frac{\\partial R_x(\\theta)}{\\partial \\theta}=-i\\frac{1}{2}XR_x(\\theta)$, which can be easily constructed using a circuit. Let's try to implement it using Paddle Quantum."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "97435cf4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original circuit: \n",
      "--Rx(1.047)--\n",
      "             \n",
      "The circuit for gradient of Rx: \n",
      "------------x----Rx(1.047)--\n",
      "            |               \n",
      "--H---SDG---*--------H------\n",
      "                            \n"
     ]
    }
   ],
   "source": [
    "# Construct the circuit with a single one-qubit gate Rx\n",
    "theta = paddle.to_tensor(np.pi / 3, 'float64')\n",
    "cir = UAnsatz(1)\n",
    "cir.rx(theta, 0)\n",
    "print('Original circuit: ')\n",
    "print(cir)\n",
    "\n",
    "print('The circuit for gradient of Rx: ')\n",
    "# The first parameter here is the index of the gate, the second parameter is the name of the gate\n",
    "print(cir.pauli_rotation_gate_partial(0, 'rx'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3d30aa3",
   "metadata": {},
   "source": [
    "It's a lot more complicated to do the same for a $u3(\\theta, \\phi, \\lambda)$ gate. But don't worry, we provide built-in methods for generating the circuits needed for calculating gradients of all parameterized single qubit gates in Paddle Quantum, i.e., $R_x$, $R_y$, $R_z$, and $u3$. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6a7e5f3c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original circuit: \n",
      "--U--\n",
      "     \n",
      "Circuits for gradient of u3: \n",
      "------------z----U--\n",
      "            |       \n",
      "--H---SDG---*----H--\n",
      "                    \n",
      "--Rz(4.706)---------y----Ry(3.292)----Rz(1.748)--\n",
      "                    |                            \n",
      "------H-------SDG---*--------H-------------------\n",
      "                                                 \n",
      "--Rz(4.706)----Ry(3.292)----z----Rz(1.748)--\n",
      "                            |               \n",
      "------H-----------SDG-------*--------H------\n",
      "                                            \n"
     ]
    }
   ],
   "source": [
    "cir = UAnsatz(1)\n",
    "theta = paddle.uniform([3], min=0.0, max=2*np.pi, dtype='float64')\n",
    "cir.u3(theta[0], theta[1], theta[2], 0)\n",
    "print('Original circuit: ')\n",
    "print(cir)\n",
    "\n",
    "# Since the u3 gate has three parameters, we need a total of three circuits. Each corresponds to one parameter.\n",
    "print('Circuits for gradient of u3: ')\n",
    "# The first parameter here is the index of the gate, the second parameter is the index of parameter\n",
    "print(cir.u3_partial(0, 0))\n",
    "print(cir.u3_partial(0, 1))\n",
    "print(cir.u3_partial(0, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95d11a2b",
   "metadata": {},
   "source": [
    "### Two-qubit gate gradient\n",
    "\n",
    "Paddle Quantum provides many two-qubit parameterized gates as well. They can be categorized into two types: one is control rotation gates like $CR_x$, the other is two-qubit rotation gates like $R_{xx}$. Circuits for gradients of two-qubit rotation gates are easy to construct. Let's take $R_{xx}$ as an example. Following the idea of one-qubit rotation gates, we first write it as $R_{xx}(\\theta)=e^{-i\\frac{\\theta}{2}X\\otimes X}$, then get the equation $\\frac{\\partial R_{xx}(\\theta)}{\\partial \\theta}=-i\\frac{1}{2}X\\otimes Xe^{-i\\frac{\\theta}{2}X\\otimes X}$, which can be converted into a circuit easily."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3fe81c6c",
   "metadata": {},
   "source": [
    "We need to be careful when calculating the gradients for control rotation gates. Usually, we will need two circuits for a control rotation gate with one parameter. For example, let's consider $CR_x(\\theta)$.\n",
    "\n",
    "$CR_x(\\theta)$ can be written as $\\left|0\\right>\\left<0\\right|\\otimes I + \\left|1\\right>\\left<1\\right|\\otimes R_x(\\theta)$, so its gradient is: \n",
    "\n",
    "$$\n",
    "\\frac{\\partial CR_x(\\theta)}{\\partial \\theta}=\\left|1\\right>\\left<1\\right|\\otimes \\frac{\\partial R_x(\\theta)}{\\partial \\theta}=-\\frac{i}{2}\\left|1\\right>\\left<1\\right|\\otimes Xe^{-i\\frac{\\theta}{2}X}.\n",
    "\\tag{15}\n",
    "$$\n",
    "\n",
    "However, this equation cannot be represented directly using one circuit. We need to use a tiny 'trick' here. Instead of using this formula directly, we decompose it into two terms \n",
    "\n",
    "$$\n",
    "\\frac{\\partial CR_x(\\theta)}{\\partial \\theta}=-\\frac{i}{4}(\\left|0\\right>\\left<0\\right|\\otimes I + \\left|1\\right>\\left<1\\right|\\otimes R_x(\\theta))I\\otimes X + \\frac{i}{4}(\\left|0\\right>\\left<0\\right|\\otimes I + \\left|1\\right>\\left<1\\right|\\otimes R_x(\\theta))Z\\otimes X.\n",
    "\\tag{16}\n",
    "$$ \n",
    "\n",
    "You can easily verify that this formula is equivalent to the former one. By doing so, we can use two circuits to compute the gradients for $CR_x$."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23a999c4",
   "metadata": {},
   "source": [
    "As always, we provide built-in methods for calculating the gradients of all two-qubit parameterized gates in Paddle Quantum, i.e., $R_{xx}$, $R_{yy}$, $R_{zz}$, $CR_x$, $CR_y$, $CR_z$, $CU$. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "59733ca2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original circuit: \n",
      "--*----Rzz(3.76)--------*------\n",
      "  |        |            |      \n",
      "--U----Rzz(3.76)----Ry(2.246)--\n",
      "                               \n",
      "The circuit for gradient of rzz: \n",
      "--*---------z---------Rzz(3.76)--------*------\n",
      "  |         |             |            |      \n",
      "--U---------|----z----Rzz(3.76)----Ry(2.246)--\n",
      "            |    |                            \n",
      "--H---SDG---*----*--------H-------------------\n",
      "                                              \n",
      "The circuit for gradient of cry: \n",
      "--*----Rzz(3.76)----y--------*------\n",
      "  |        |        |        |      \n",
      "--U----Rzz(3.76)----|----Ry(2.246)--\n",
      "                    |               \n",
      "--H-------SDG-------*--------H------\n",
      "                                    \n",
      "--*----Rzz(3.76)---------y--------*------\n",
      "  |        |             |        |      \n",
      "--U----Rzz(3.76)----z----|----Ry(2.246)--\n",
      "                    |    |               \n",
      "--H--------S--------*----*--------H------\n",
      "                                         \n"
     ]
    }
   ],
   "source": [
    "theta = paddle.uniform([5], min=0.0, max=2*np.pi, dtype='float64')\n",
    "cir = UAnsatz(2)\n",
    "cir.cu(theta[0], theta[1], theta[2], [0, 1])\n",
    "cir.rzz(theta[3], [0, 1])\n",
    "cir.cry(theta[4], [0, 1])\n",
    "print('Original circuit: ')\n",
    "print(cir)\n",
    "\n",
    "# The first parameter here is the index of the gate, the second parameter is the index of parameter\n",
    "# Since we have three parameters for cu gate, and we need two circuits for each parameter, we have a total of 6 circuits.\n",
    "# Circuits for gradients of cu:\n",
    "cu3_00 = cir.cu3_partial(0, 0)[0]\n",
    "cu3_01 = cir.cu3_partial(0, 0)[1]\n",
    "cu3_10 = cir.cu3_partial(0, 1)[0]\n",
    "cu3_11 = cir.cu3_partial(0, 1)[1]\n",
    "cu3_20 = cir.cu3_partial(0, 2)[0]\n",
    "cu3_21 = cir.cu3_partial(0, 2)[1]\n",
    "\n",
    "# The first parameter here is the index of the gate, the second parameter is the name of the gate\n",
    "print('The circuit for gradient of rzz: ')\n",
    "print(cir.pauli_rotation_gate_partial(1, 'RZZ_gate'))\n",
    "\n",
    "# The first parameter here is the index of the gate, the second parameter is the name of the gate\n",
    "print('The circuit for gradient of cry: ')\n",
    "print(cir.control_rotation_gate_partial(2, 'cry')[0])\n",
    "print(cir.control_rotation_gate_partial(2, 'cry')[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d264a86",
   "metadata": {},
   "source": [
    "Now that we have all individual circuits prepared for calculating gradients, the next step is to get the exact value of the gradients. How to do so? We need to plug these circuits into our objective function, then the results are our desired gradients. For gates like $CR_x$, we will take the mean of the two circuits to be the gradient, as indicated in the analytical formula. We also provide a built-in method (Note: The built-in method currently does not support assigning an input state or running on a noisy circuit):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "02e8ea72",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--U----*----x----Ry(0.667)--\n",
      "       |    |               \n",
      "--U----x----*----Ry(4.807)--\n",
      "                            \n",
      "Gradient of this objective function is:  [ 0.         -0.76471634  0.00700639  0.         -0.29062181 -0.01701887\n",
      " -0.07729092  0.7766131 ]\n"
     ]
    }
   ],
   "source": [
    "# Randomly generate parameters for our circuit\n",
    "theta = paddle.uniform(shape=[8], dtype='float64', min=0.0, max=np.pi * 2)\n",
    "theta.stop_gradient = False\n",
    "\n",
    "# Construct circuit of U(theta)\n",
    "cir = UAnsatz(2)\n",
    "cir.complex_entangled_layer(theta[:6], 1)\n",
    "cir.ry(theta=theta[6], which_qubit=0)\n",
    "cir.ry(theta=theta[7], which_qubit=1)\n",
    "cir.run_state_vector()\n",
    "print(cir)\n",
    "\n",
    "# Calculate gradient using our built-in method\n",
    "# We pass in our Hamiltonian H used in the objective function\n",
    "gradient = cir.linear_combinations_gradient(H, shots=0)\n",
    "print(\"Gradient of this objective function is: \", gradient.numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7fcdbdf",
   "metadata": {},
   "source": [
    "## Application: Simulating VQE with Paddle Quantum\n",
    "\n",
    "Variational Quantum Eigensolver (VQE) [3] is designed to find the ground state energy of a given molecular Hamiltonian using variational quantum circuits. Interested readers can find more details from the previous tutorial [VQE](../quantum_simulation/VQE_EN.ipynb).\n",
    "\n",
    "We will demonstrate how to use VQE to find the ground state energy for the Hamiltonian of hydrogen molecule $H_2$. In the process, we will use the methods introduced above to calculate the gradient."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e9d6e7b",
   "metadata": {},
   "source": [
    "### Using Paddle's Optimizer\n",
    "\n",
    "First, we will use Paddle's optimizer Adam to run our example. We can choose using either finite difference method or parameter-shift method to calculate gradient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "cce057c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from paddle_quantum.VQE.chemistrysub import H2_generator\n",
    "from paddle_quantum.expecval import ExpecVal\n",
    "\n",
    "# Set up our Hamiltonian H\n",
    "pauli_str, N = H2_generator()\n",
    "H = Hamiltonian(pauli_str)\n",
    "\n",
    "# Hyper-parameters\n",
    "ITR = 80  # Set the number of optimization iterations\n",
    "LR = 0.4   # Set the learning rate\n",
    "D = 2      # Set the depth of the repetitive calculation module in QNN\n",
    "\n",
    "def U_theta(theta, Hamiltonian, N, D):\n",
    "    \"\"\"\n",
    "    Quantum Neural Network\n",
    "    \"\"\"\n",
    "    # Initialize the quantum neural network according to the number of qubits N\n",
    "    cir = UAnsatz(N)\n",
    "\n",
    "    # Built-in {R_y + CNOT} circuit template\n",
    "    theta = paddle.reshape(theta, [D+1, N, 1])\n",
    "    cir.real_entangled_layer(theta[:D], D)\n",
    "\n",
    "    # Lay R_y gates in the last row\n",
    "    for i in range(N):\n",
    "        cir.ry(theta=theta[D][i][0], which_qubit=i)\n",
    "\n",
    "    # The quantum neural network acts on the default initial state |0...0>\n",
    "    cir.run_state_vector()\n",
    "    \n",
    "    return cir"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0cdee79",
   "metadata": {},
   "source": [
    "Here in our forward propagation mechanism, we use the updated parameters to calculate gradient using parameter-shift rule, and calculate the expectation value. You can change the method to 'finite_diff' if you'd like to try it out using finite difference method. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0d172081",
   "metadata": {},
   "outputs": [],
   "source": [
    "class StateNet(paddle.nn.Layer):\n",
    "\n",
    "    def __init__(self, cir):\n",
    "        super(StateNet, self).__init__()\n",
    "        \n",
    "        self.cir = cir\n",
    "        params = cir.get_param()\n",
    "        \n",
    "        # Assign the theta parameter list to be the trainable parameter list of the circuit\n",
    "        self.theta = self.create_parameter(shape=[len(params)], \n",
    "                                           default_initializer=paddle.nn.initializer.Assign(params),\n",
    "                                           dtype='float32', is_bias=False)\n",
    "        \n",
    "    # Define loss function and forward propagation mechanism\n",
    "    def forward(self):\n",
    "        # Calculate the loss function/expectation value using Parameter-shift rule to calculate gradient\n",
    "        loss = ExpecVal.apply(self.cir, self.theta.cast('float64'), 'param_shift', H, shots=0)\n",
    "        \n",
    "        return loss, self.cir"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0b8235c9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "iter: 20 loss: -1.1114\n",
      "iter: 20 Ground state energy: -1.1114 Ha\n",
      "iter: 40 loss: -1.1316\n",
      "iter: 40 Ground state energy: -1.1316 Ha\n",
      "iter: 60 loss: -1.1357\n",
      "iter: 60 Ground state energy: -1.1357 Ha\n",
      "iter: 80 loss: -1.1361\n",
      "iter: 80 Ground state energy: -1.1361 Ha\n",
      "\n",
      "The trained circuit:\n",
      "--Ry(6.282)----*--------------x----Ry(6.289)----*--------------x----Ry(3.148)--\n",
      "               |              |                 |              |               \n",
      "--Ry(3.138)----x----*---------|----Ry(0.207)----x----*---------|----Ry(3.142)--\n",
      "                    |         |                      |         |               \n",
      "--Ry(6.278)---------x----*----|----Ry(0.001)---------x----*----|----Ry(3.143)--\n",
      "                         |    |                           |    |               \n",
      "--Ry(0.001)--------------x----*----Ry(3.156)--------------x----*----Ry(3.154)--\n",
      "                                                                               \n",
      "\n",
      "Ground state energy obtained:  [-1.13609609] Ha\n",
      "Actual ground state energy:  -1.13618 Ha\n"
     ]
    }
   ],
   "source": [
    "# Initialize the theta parameter list and fill the initial value with a uniform distribution of [0, 2*pi]\n",
    "theta = paddle.to_tensor(np.random.uniform(0.0, 2*np.pi, (D+1) * N), stop_gradient=False)\n",
    "\n",
    "# Initialize the circuit\n",
    "cir = U_theta(theta, H, N, D)\n",
    "\n",
    "# Determine the parameter dimension of the network\n",
    "net = StateNet(cir)\n",
    "\n",
    "# Generally speaking, we use Adam optimizer to obtain relatively good convergence,\n",
    "# You can change it to SGD or RMS prop.\n",
    "opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
    "\n",
    "# Record optimization results\n",
    "summary_iter, summary_loss = [], []\n",
    "\n",
    "# Optimization loop\n",
    "for itr in range(1, ITR + 1):\n",
    "\n",
    "    # Forward propagation to calculate loss function\n",
    "    loss, cir = net()\n",
    "\n",
    "    # Use back propagation to minimize the loss function\n",
    "    loss.backward()\n",
    "    opt.minimize(loss)\n",
    "    opt.clear_grad()\n",
    "\n",
    "    # Record optimization results\n",
    "    summary_loss.append(loss.numpy())\n",
    "    summary_iter.append(itr)\n",
    "\n",
    "    # Print result\n",
    "    if itr % 20 == 0:\n",
    "        print(\"iter:\", itr, \"loss:\", \"%.4f\" % loss.numpy())\n",
    "        print(\"iter:\", itr, \"Ground state energy:\", \"%.4f Ha\" \n",
    "                                            % loss.numpy())\n",
    "    if itr == ITR:\n",
    "        print(\"\\nThe trained circuit:\")\n",
    "        print(cir)\n",
    "\n",
    "print('\\nGround state energy obtained: ', summary_loss[-1], \"Ha\")\n",
    "print('Actual ground state energy: ', -1.13618, \"Ha\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e672bed",
   "metadata": {},
   "source": [
    "We can see that the ground state energy we obtained is close to the theoretical value."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d58ebab",
   "metadata": {},
   "source": [
    "### Using SciPy's Optimizer\n",
    "\n",
    "We will also demonstrate how to use SciPy's optimizer to run VQE easily with Paddle Quantum. For this example, we will use Conjugate Gradient (CG) optimizer along with linear combination method to find the ground state energy of our Hamiltonian. \n",
    "\n",
    "Other SciPy methods we support include Newton-CG, Powell, and SLSQP."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "7f7ef671",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loss:  [-0.91176578]\n",
      "loss:  [-1.03555093]\n",
      "loss:  [-1.11965221]\n",
      "loss:  [-1.13435502]\n",
      "loss:  [-1.13577104]\n",
      "loss:  [-1.13615947]\n",
      "loss:  [-1.13618601]\n",
      "loss:  [-1.13618942]\n",
      "loss:  [-1.13618945]\n",
      "loss:  [-1.13618945]\n",
      "loss:  [-1.13618945]\n",
      "Optimization terminated successfully.\n",
      "Actual ground state energy:  -1.13618 Ha\n"
     ]
    }
   ],
   "source": [
    "from paddle_quantum.optimizer import ConjugateGradient\n",
    "\n",
    "# Initialize the circuit\n",
    "cir = U_theta(theta, H, N, D)\n",
    "\n",
    "optimizer = ConjugateGradient(cir, H, shots=0, grad_func_name='linear_comb')\n",
    "optimizer.minimize(iterations=80)\n",
    "print('Actual ground state energy: ', -1.13618, \"Ha\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ad4927e",
   "metadata": {},
   "source": [
    "## Conclusion\n",
    "\n",
    "As you can see, finite-difference and parameter-shift methods have similar forms - both of them require two function evaluations per parameter. The benefits of these methods are that the gradients can be calculated without knowing much about the circuit or the objective function. We can treat them as a black box and get the gradient just by feeding in different parameters. Our preferred choice between those two is parameter-shift method because its result is an analytical gradient, while finite difference method can only get an estimation of the gradient. However, parameter-shift only applies to $U(\\theta)$ that can be generated by $G$ that has two distinct eigenvalues:  $U(\\theta) = e^{-ia\\theta G}$ or can be decomposed into a product of gates in this form.\n",
    "\n",
    "Using linear combination of unitary gates to calculate the gradients of a given circuit is probably the most straightforward analytical method. By differentiating unitary gates under their mathematical forms, we can use circuits to represent the resulting formula. The number of circuits required is proportional to the number of parameters in the original circuit as the other two methods. We can even calculate gradients by constructing only one single circuit for simple gates like $R_x$, $R_{xx}$ and etc. However, note that we will use an ancilla qubit in this method. Moreover, you might have noticed that this method takes a long time to run on complex circuits. That's because as the number of qubits increases, the number of circuits used to represent the first order differentiation of a single multi-qubit gate also increases. "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26a8f5fd",
   "metadata": {},
   "source": [
    "_______\n",
    "\n",
    "## References\n",
    "\n",
    "[1] Crooks, Gavin E. \"Gradients of parameterized quantum gates using the parameter-shift rule and gate decomposition.\" [arXiv preprint arXiv:1905.13311 (2019)](https://arxiv.org/abs/1905.13311).\n",
    "\n",
    "[2] Somma, Rolando, et al. \"Simulating physical phenomena by quantum networks.\" [Physical Review A 65.4 (2002): 042323](https://arxiv.org/abs/quant-ph/0108146).\n",
    "\n",
    "[3] Peruzzo, Alberto, et al. \"A variational eigenvalue solver on a photonic quantum processor.\" [Nature communications 5.1 (2014): 1-7](https://www.nature.com/articles/ncomms5213).\n",
    "\n",
    "[4] Schuld, Maria, et al. \"Evaluating analytic gradients on quantum hardware.\" [Physical Review A 99.3 (2019): 032331](https://arxiv.org/abs/1811.11184)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
